import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../providers/ApiPro.service';
import {
    FormBuilder,
    FormGroup,
    FormControl,
    Validators
} from '@angular/forms';
  import { NzModalService } from 'ng-zorro-antd';

  import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';


@Component({
  selector: 'app-userLogin',
  templateUrl: './userLogin.component.html',
  styleUrls: ['./userLogin.component.scss']
})
export class UserLoginComponent implements OnInit {

  validateForm: FormGroup;
  PasswordForm: FormGroup;

  public token: string;
  public phoneNum: string;
  public mobile: string;
  public validCode: string;

  isVisible = false;
  isPassWord = false;
  truePw = false;
  trueCode = false;
  isConfirmLoading = false;
  isLoadingOne = false;

  times = 60;

  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
  }

  _pwsubmit() {
    for (const i in this.PasswordForm.controls) {
      this.PasswordForm.controls[ i ].markAsDirty();
    }
    if(this.PasswordForm.valid==true){
      this.editPassW();
    } 
  }

  constructor(
  private fb: FormBuilder,
  private pw: FormBuilder,
  public apiService: ApiService,
  public router: Router,
  private confirmServ: NzModalService,
) { }

  ngOnInit() {
     this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required ] ],
      passWord: [ null, [ Validators.required ] ],
      // remember: [ true ],
    });
    this.PasswordForm = this.pw.group({
      password: [ null, [ Validators.required,this.pwValidator ] ],
      checkPassword: [ null, [ Validators.required, this.confirmationValidator ] ],
    });
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.PasswordForm.controls[ 'password' ].value) {
      return { confirm: true, error: true };
    }
  };

  pwValidator = (control: FormControl): { [s: string]: boolean } => {
    const pw_REGEXP = /^(?=.*[a-z,A-Z])(?=.*\d)[\s\S]{8,16}$/;
    if (!control.value) {
      return { required: true }
    } else if (!pw_REGEXP.test(control.value)) {
      return { error: true, password: true };
    }
  };

  //登入
  loadIng(){
    this._submitForm();
    let url = "login";
    this.apiService.Postformdata(url,this.validateForm.value)
      .then(res =>{
        this.token = res.result.token;
        localStorage.setItem("userName",res.result.userName);
        this.apiService.setLocalStroage(this.token);
        console.log(this.apiService.getLocalStroage());
        this.truePw = false;
        setTimeout(_ =>{
          this.router.navigateByUrl("layout");
        },300)
      })
      .catch(err =>{
        this.truePw = true;
      })
  }

  //点击发送验证码
  loadOne = (value) => {
    let url = "sendmessage"
    // let mobile = this.validateForm.value.userName;
    
    this.isLoadingOne = true;
    this.apiService.post2(url,{"mobile":this.mobile})
      .then(res =>{
        console.log(res);
      })
    this.loadLow();
    setTimeout(_ => {
      this.isLoadingOne = false;
    }, 60000);
  };

  loadLow(){
   let set =  setInterval( _ => {
      this.times--;
      if(this.times == 0){
        clearInterval(set)
        this.times = 60;
      }
    },1000)
  }




  
  showModal = () => {
    this.isVisible = true;
    this.mobile = this.validateForm.value.userName;
    // this.mobile=this.mobile.substr(0,3)+'****'+this.mobile.substr(7,10);
  }

  // 验证验证码
  handleOk = (e) => {
    let est = {
      mobile:"",
      validCode:""
    };
    let url = "validmessage";
    est.mobile = this.mobile;
    est.validCode = this.validCode;
    console.log(est);
    this.apiService.Postformdata(url,est)
      .then(res =>{
        console.log(res);
        if(res.errCode == 0){
          this.isConfirmLoading = true;
          setTimeout(() => {
            this.isVisible = false;
            this.isConfirmLoading = false;
            this.isPassWord = true;
            this.trueCode = false;            
          }, 800);
        }else{
            this.trueCode = true;  
        }
      }).catch(err =>{
        this.trueCode = true;        
      })
    
   
  }

  handleCancel = (e) => {
    this.isVisible = false;
  }

   handlePw = (e) => {
    this.isPassWord = false;
  }

   getFormControl(name) {
    return this.PasswordForm.controls[ name ];
  }
    updateConfirmValidator() {
      this.PasswordForm.controls['password']
    /** wait for refresh value */
    setTimeout(_ => {
      this.PasswordForm.controls[ 'checkPassword' ].updateValueAndValidity();
    });
  }

  editPassW(){
    let url = "resetpwd"
    let body = {
      mobile:'',
      pwd:''
    }
    body.mobile = this.mobile;
    body.pwd = this.PasswordForm.value.checkPassword;
    this.apiService.post2(url,body)
    .then(res =>{
      console.log(res);
      if(res.result){
          this.isPassWord = false;
          setTimeout(_ => {
            this.success();            
          }, 200);
      }else{
        return ;
      }
    })
  }

  success(){
    let self = this;
      this.confirmServ.success({
      title: '成功',
      content: '密码修改完成',
      okText:'确定',
      onOk() {
      },

    });
  }

}
